package com.yigou.alipay.controller;

import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yigou.alipay.config.AliPayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/index")
public class IndexController {

    @RequestMapping("/pay")
    @ResponseBody
    //参数 1.订单号 2.订单名称 3.付款金额 4. 商品描述
    public void pay(HttpServletRequest request, HttpServletResponse response) throws Exception {

//        AliPayConfig aliPayConfig = new AliPayConfig();

        //1）封装RSA签名
        // 参数 1.网关 2.AppID 3.私钥 4.返回数据的格式 5.编码 6.公钥 7.签名
        DefaultAlipayClient client = new DefaultAlipayClient(
                AliPayConfig.gatewayUrl,
                AliPayConfig.app_id,
                AliPayConfig.merchant_private_key,
                "json",
                AliPayConfig.charset,
                AliPayConfig.alipay_public_key,
                AliPayConfig.sign_type
                                          );

        //2)创建request请求
        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();

        //3)封装对象
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
        //商品描述，可空
        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");


        payRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //异步回调的地址，成功页
        payRequest.setNotifyUrl(AliPayConfig.notify_url);
        //同步回调的地址，扫码支付页
        payRequest.setReturnUrl(AliPayConfig.return_url);

        // 生成表单
        String head = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head>";
        String result = client.pageExecute(payRequest).getBody();
        String end = "<body> </body></html>";
        System.out.println(result);
        //输出
        response.getWriter().println(head + result + end);
    }
}
